package AdminService

import (
	"database/sql"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/BaseService"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	condition := g.Map{}
	obj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	countObj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	// 默认全部表别名先设置为 a
	asName := "a"
	// 处理查询的列
	selectFields := ""
	defaultSelectFields := strings.Split(obj.GetFieldsStr(), ",")

	pageQueryOp := req.PageQueryOp
	if pageQueryOp != nil {
		if pageQueryOp.AsName != "" {
			asName = pageQueryOp.AsName
		}
	}
	// 有设置表别名
	obj.As(asName)
	countObj.As(asName)
	// 获取查询条件
	BaseService.GetCondition(r, condition, pageQueryOp, asName)
	obj.Where(
		condition,
	)
	countObj.Where(
		condition,
	)

	if pageQueryOp != nil {
		if len(pageQueryOp.SelectFields) > 0 {
			// 设置了 select 的
			selectFields = strings.Join(pageQueryOp.SelectFields, ",")
		}
		if pageQueryOp.OrderBy != "" {
			obj.Order(pageQueryOp.OrderBy)
		}
	}
	// 设置 select
	if selectFields != "" {
		obj.Fields(selectFields)
	} else {
		for k, v := range defaultSelectFields {
			defaultSelectFields[k] = asName + "." + v
		}
		obj.Fields(strings.Join(defaultSelectFields, ","))
	}
	// 处理查询里 --- end ---
	// 设置 删除时间
	obj.Where(asName + ".delete_at < 1")
	countObj.Fields("1").Where(asName + ".delete_at < 1")

	if pageQueryOp != nil {
		for _, item := range pageQueryOp.LeftJoin {
			obj.LeftJoin(item.TableInfo, item.Condition)
		}
	}
	count, countErr := countObj.Count()
	if countErr != nil {
		return response.FailByRequestMessage(nil, countErr.Error())
	}
	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	// 获取角色名
	resList := res.List()
	for _, item := range resList {
		item["roleName"] = getRoleNameByAdminId(r, gconv.String(item["id"]))
		item["avatar_profix"] = g.Cfg().GetString("upload.PhotoPreFix")
	}

	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}

func getRoleNameByAdminId(r *ghttp.Request, adminId string) string {
	var arList []g.Map
	arListTmp, _ := g.Redis().DoVar("HGET", "admin_role", "getRoleNameByAdminId")
	if arListTmp.IsEmpty() {
		// 取出全部的 admin_role ，防止下次再读数据库
		tmp, err := toolsDb.GetUnSafaTableAddDeleteWhere(r.GetCtx(), "admin_role").Fields(
			"admin_id,role_id").All()
		if err != nil {
			return ""
		}
		arList = tmp.List()
		g.Redis().Do("HSET", "admin_role", "getRoleNameByAdminId", tmp.Json())
		g.Redis().Do("EXPIRE", "admin_role", 60)
	} else {
		arList = arListTmp.Maps()
	}

	var roleList []g.Map
	roleListTmp, _ := g.Redis().DoVar("HGET", "sys_role", "getRoleNameByAdminId")

	if roleListTmp.IsEmpty() {
		tmp, err := toolsDb.GetUnSafaTableAddDeleteWhere(r.GetCtx(), "sys_role").Fields(
			"id,name").All()
		if err != nil {
			return ""
		}
		roleList = tmp.List()
		g.Redis().Do("HSET", "sys_role", "getRoleNameByAdminId", tmp.Json())
		g.Redis().Do("EXPIRE", "sys_role", 60)
	} else {
		roleList = roleListTmp.Maps()
	}
	//fmt.Println("arList ",arList)
	//fmt.Println("roleList ",roleList)
	roleNames := []string{}
	for _, item := range arList {
		//fmt.Println("roleList ",gconv.String(item["admin_id"]) != adminId)
		if gconv.String(item["admin_id"]) != adminId {
			continue
		}
		for _, role := range roleList {
			if item["role_id"] != role["id"] {
				continue
			}
			roleNames = append(roleNames, gconv.String(role["name"]))
		}
	}

	return strings.Join(roleNames, ",")
}
